package hk.guosen.weix.svlt;

import java.io.IOException;

import hk.guosen.weix.EnCodingType;
import hk.guosen.weix.client.WeixClient;
import hk.guosen.weix.client.msg.SignResp;
import hk.guosen.weix.client.msg.WeixClientId;
import hk.guosen.weix.client.util.Cache;
import hk.guosen.weix.client.util.CacheManager;
import hk.guosen.weix.client.util.JsonUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * 微信js调用签名服务
 */
public  class WeixSignServlet  extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	private WeixClient clt;
	
	public WeixSignServlet()
	{
	
		clt=new WeixClient(new WeixClientId("wx2199742959b14fd7", "849bbd1fbac5121d240b697bc3d93145"));
		clt.startAutoLogin();
		
	}
	/**
	 * 处理签名信息
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		String result="";
		SignResp signResp=new SignResp();
		String url = request.getParameter("url");
		Cache cache=CacheManager.getCacheInfo(url);
		if(cache!=null)
		{
			signResp=(SignResp)cache.getValue();
		}
		else
		{
			 signResp=clt.sign(url);
			 CacheManager.putCacheInfo(url,signResp, 7200);
		}
	    result=JsonUtil.bean2Json(signResp);
		if(result != null)
		{
			response.setCharacterEncoding(EnCodingType.UTF_8);
			response.getWriter().write(result);
			response.getWriter().close();
		}
	}
}
